package ke24.ga.extension;
import com.softhinker.ke24.unit2.data.DataRetriever;


import ke24.ga.Package;
public class PackageGenerator implements DataRetriever{
    
    private Package[] packages;
    public PackageGenerator() {
        this.packages = generate();
    }
    /*
     * return a quantity number of packages with weight in the range of min..max (inclusive)
     */
    public static Package[] generatePackage(int startID, int endID, int min, int max) {
        if (startID < 0) return null;
        if (startID > endID) return null;
        if (min > max) return null;
        Package[] result = new Package[endID - startID + 1];
        for (int i = startID; i <= endID; i++) {
            int weight = min + (int)(Math.random() * (max - min + 1));
            result[i - startID] = new Package(i, weight);
        }
        return result;
    }
    
    public Package[] generate() {
        Package[] big = PackageGenerator.generatePackage(1, 16, 100, 400);
        Package[] small = PackageGenerator.generatePackage(17, 48, 50, 200);
        
        //generate package array of 64 places that hold 48 pakcages
        Package[] result = new Package[64];
         
        for (int i = 0; i < result.length; i++) {
            // Set a weight between 290 and 310
            // double weight = 290 + Math.random() * 20;            
            if (i < 32) {                
                int id = (i / 8) * 4 + i % 4;
                
                
                result[i] = new Package(big[id].getId(),big[id].getWeight()/2);
            }else {
                result[i] = new Package(small[i - 32].getId(),small[i - 32].getWeight());
            }
            
        }
        return result;
    }
    
    public Object[][] retrieveData() {
        Package[] pkgs = this.packages;
        Object[][] data = new Object[pkgs.length][5];
        
        
        double groupWeight = 0;
        for(int i = 0; i < pkgs.length; i++)
        {
            if (i%4 == 0) groupWeight = 0;
            groupWeight += pkgs[i].getWeight();
            data[i][0] = getLocation(i);
            data[i][1] = Package.isBig( pkgs[i].getId())?"Big":"Small";
            data[i][2] = pkgs[i].getId();
            data[i][3] = pkgs[i].getWeight();                        
            data[i][4] = groupWeight;
            if (i%4 == 3) {
                data[i-1][4] = data[i-2][4] = data[i-3][4] = data[i][4];
            }
        }
        return data;
    }
    
    public String[] getColumnNames() {
        String[] columns = {"Position","Type", "Package ID","Weight",  "Group Weight"};
        return columns;
    }
    
    public Package[] getPackages() {
        return this.packages;
    }

    private String getLocation(int i) {
        int group = i/4 + 1;
        int level = i % 4 + 1;
        return group + "" + level;        
    }
    
    
    
}
